package com.alcj.controller;

import com.alcj.common.base.BaseController;
import com.alcj.common.constant.SysConstant;
import com.alcj.common.utils.CmnUtil;
import com.alcj.model.*;
import com.alcj.service.SelfProjectService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : LiangZhao
 * @version :v1.0
 * @Package : com.alcj.controller
 * @Description : 自检项目控制器
 * @date : 2017/10/13 13:40
 */
@Controller
@RequestMapping("/self")
public class SelfProjectController extends BaseController{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 车辆自检业务接口
     */
    @Autowired
    SelfProjectService selfProjectService;


    /**
     *车辆自检初期化
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/selfindex")
    public String register(HttpServletRequest request, Model model) {

        try {
            // 页面显示自检项目
            List<SelfPCategory> selfList = new ArrayList<SelfPCategory>();
            // 获取自检项目大分类
            List<SelfPCategory> sellfPC = selfProjectService.getSelfPCategory();
            // 获取自检项目小分类
            if(sellfPC != null && sellfPC.size() > 0){

                // 循环设置自检项目
                for(SelfPCategory pc : sellfPC){
                    SelfMCategory selfMCategory = new SelfMCategory();
                    selfMCategory.setSpcNo(pc.getSpcNo());
                    selfMCategory.setSprUser("123");
                    pc.setSelfMCategory(selfProjectService.getSelfMCategory(selfMCategory));
                    // 将自检项目放在self
                    selfList.add(pc);
                }
            }

            model.addAttribute("selfList", selfList);
        } catch (Exception e) {
            // 异常报错
            logger.error("获取用户中心信息异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "selfCheck";
    }

    /**
     *获取自检项目图片
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/selfimg")
    @ResponseBody
    public JSONObject getSelfImg(HttpServletRequest request, Model model) {
        try {
            int sprId = Integer.parseInt(request.getParameter("smcid"));

            // 设定检索条件
            List<SelfImg> resultInfo = selfProjectService.getSelfImg(sprId);

            // 初期设定信息
            if (!CmnUtil.isEmpty(resultInfo)) {
                model.addAttribute("data", resultInfo);
            } else {
                model.addAttribute("data", null);
            }

            JSONObject jsonImg = new JSONObject();
            jsonImg.put("selfimg",resultInfo);
            return jsonImg;
        } catch (Exception e) {
            // 异常报错
            logger.error("获取自检项目图片异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
//            return SysConstant.ERROR_PAGE_500;
            return null;
        }
    }

    /**
     * 自动保存自检信息
     * @param request
     * @param model
     * @return String
     */
    @RequestMapping(value = "/selfCheck")
    @ResponseBody
    public void editSelfCheck(HttpServletRequest request, Model model) {
        try {

            // 获取JSON字符串
            String jsonString = request.getParameter("data");

            if (jsonString != null && !"".equals(jsonString)){
                // 转换为json对象
                JSONObject jsonObject = JSON.parseObject(jsonString);
                // 获取json对象中的数组
                JSONArray smcIdArray = jsonObject.getJSONArray("smcId");
                JSONArray sprResultArray = jsonObject.getJSONArray("sprResult");

                List<SelfProject> selfList = new ArrayList<SelfProject>();
                // 判断获取数据是否正确
                if(smcIdArray.size() != sprResultArray.size()){
                    // 异常报错
                    logger.error("获取自检结果数据异常 : {}");
                    logger.error("异常详细信息 :");
                }else{
                    // 循环获取数据放入实体类中
                    for (int i = 0; i < smcIdArray.size(); i++){
                        // 放入自检项目实体类中
                        SelfProject self = new SelfProject();
                        self.setSmcId(smcIdArray.getIntValue(i));
                        self.setSprResult(sprResultArray.getString(i));
                        // TODO 用户ID
                        self.setSprUser("123");

                        // 共通字段
                        self.setSprDel("0");
                        self.setSprInuser("123");
                        self.setSprUpuser("123");
                        selfList.add(self);
                    }
                }
                // 保存自检结果
                int save = selfProjectService.addSelfProject(selfList, "123");
            }

        } catch (Exception e) {
            // 异常报错
            logger.error("保存自检结果数据异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
        }
    }

    /**
     * 保存自检信息跳转到自检报告
     * @param request
     * @param model
     * @return String
     */
    @RequestMapping(value = "/selfForm")
    public String editSelfForm(HttpServletRequest request, Model model) {
        try {

            // 获取JSON字符串
            String jsonString = request.getParameter("data");

            if (jsonString != null && !"".equals(jsonString)){
                // 转换为json对象
                JSONObject jsonObject = JSON.parseObject(jsonString);
                // 获取json对象中的数组
                JSONArray smcIdArray = jsonObject.getJSONArray("smcId");
                JSONArray sprResultArray = jsonObject.getJSONArray("sprResult");

                List<SelfProject> selfList = new ArrayList<SelfProject>();
                // 判断获取数据是否正确
                if(smcIdArray.size() != sprResultArray.size()){
                    // 异常报错
                    logger.error("获取自检结果数据异常 : {}");
                    logger.error("异常详细信息 :");
                    return SysConstant.ERROR_PAGE_500;
                }else{
                    // 循环获取数据放入实体类中
                    for (int i = 0; i < smcIdArray.size(); i++){
                        // 放入自检项目实体类中
                        SelfProject self = new SelfProject();
                        self.setSmcId(smcIdArray.getIntValue(i));
                        self.setSprResult(sprResultArray.getString(i));
                        // TODO 用户ID
                        self.setSprUser("123");

                        // 共通字段
                        self.setSprDel("0");
                        self.setSprInuser("123");
                        self.setSprUpuser("123");
                        selfList.add(self);
                    }
                }
                // 保存自检结果
                int save = selfProjectService.addSelfProject(selfList, "123");
            }

            // 开始组装自检报告页面的内容
            List<SelfPCategory> selfList = new ArrayList<SelfPCategory>();
            // 获取自检项目大分类
            List<SelfPCategory> sellfPC = selfProjectService.getSelfPCategory();
            // 获取自检项目小分类
            if(sellfPC != null && sellfPC.size() > 0){

                // 循环设置自检项目
                for(SelfPCategory pc : sellfPC){
                    SelfMCategory selfMCategory = new SelfMCategory();
                    selfMCategory.setSpcNo(pc.getSpcNo());
                    selfMCategory.setSprUser("123");

                    List<SelfMCategory> smcList = selfProjectService.getSelfMCategory(selfMCategory);
                    pc.setSelfMCategory(smcList);

                    // 判定大项是否合格
                    if (smcList != null && smcList.size() > 0){
                        // 先设置为全部合格
                        pc.setIsOk(0);
                        // 遍历小项是否有不合格项目
                        for(SelfMCategory smc : smcList){
                            if(!"0".equals(smc.getSprResult())){
                                pc.setIsOk(1);
                                break;
                            }
                        }
                    }else{
                        pc.setIsOk(0);
                    }
                    // 将自检项目放在self
                    selfList.add(pc);
                }
            }

            model.addAttribute("selfList", selfList);

        } catch (Exception e) {
            // 异常报错
            logger.error("保存自检结果数据异常 : {}", e.getMessage());
            logger.error("异常详细信息 :",e);
            return SysConstant.ERROR_PAGE_500;
        }
        return "selfCheckReport";
    }
}
